package com.zg.common.web.socket;

import com.zg.common.core.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.Session;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Zxb
 */
@RestController
@Api(tags = {"推送功能"})
public class WebSocketPushController {

    @ApiOperation("查看所有客户端")
    @GetMapping("/push/client/all")
    public R<?> listAllClient() {
        ConcurrentHashMap<String, List<Session>> clientPool = WebSocketServer.clientPool;
        return R.success(clientPool.keys());
    }

    @ApiOperation("给单个客户端推送消息")
    @GetMapping("/push/msg/one")
    public R<?> pushToOne(String clientId, String msg) {
        WebSocketServer.sendMsg(clientId, msg);
        return R.success();
    }

    @ApiOperation("给所有客户端推送消息")
    @GetMapping("/push/msg/all")
    public R<?> pushToAll(String msg) {
        WebSocketServer.sendMsg(msg);
        return R.success();
    }

    @ApiOperation("测试推送导入进度")
    @GetMapping("/push/import/test")
    public R<?> testImport(String clientId, Integer count) {
        for (int i = 1; i <= count; i++) {
            try {
                Thread.sleep(200);
                System.out.println(clientId+":"+"process:" + i);
                WebSocketServer.sendMsg(clientId, "process:" + i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return R.success();
    }
}
